Skip to main content

Problem Set 6 Key: Shrinkage and Cross-Validation

PLS 206 — Applied Multivariate Modeling

Author

Grey Monroe

Published

January 1, 2026

Tip

Try the problems yourself before consulting this key. Every number below was checked in R 4.5.1 (lme4, lmerTest, glmnet) against data/almond_orchards.csv (174 trees, 14 orchards) and data/wild_wheat.csv (54 genotypes) on 2026-11-01. The orchard data are simulated: canopy raises yield by 0.08 kg per percentage point in every orchard, orchards differ in baseline (SD 1.2 kg), and the inoculant does nothing.

library(ggplot2)
library(lme4)
library(lmerTest)
library(glmnet)
orch  <- read.csv("https://greymonroe.github.io/PLS_206/data/almond_orchards.csv")
wheat <- read.csv("https://greymonroe.github.io/PLS_206/data/wild_wheat.csv")

Part 1: Trees Within Orchards

Q1. The slope is about the same three ways, but the model that ignores orchard has a wider standard error:

Model canopy slope SE
ignore orchard, lm() 0.0742 0.0074
orchard fixed, lm() 0.0805 0.0056
orchard random, lmer() 0.0799 0.0055

Mixed model: orchard SD 1.17 kg/tree, residual SD 1.03 kg/tree. The plain lm() has a residual SD of 1.42: with orchard left out, the orchard-to-orchard differences end up in the residuals, on top of the tree-to-tree scatter. The mixed model splits that scatter into its two sources. The figure should show the coloured clusters sitting above and below the single line, orchard by orchard.

m_pool <- lm(yield ~ canopy, data = orch)
m_fix  <- lm(yield ~ canopy + orchard, data = orch)
m_mix  <- lmer(yield ~ canopy + (1 | orchard), data = orch)
coef(summary(m_pool))["canopy", ]   # 0.0742, SE 0.0074
coef(summary(m_fix))["canopy", ]    # 0.0805, SE 0.0056
coef(summary(m_mix))["canopy", ]    # 0.0799, SE 0.0055
VarCorr(m_mix)                      # orchard 1.1743, Residual 1.0297
sigma(m_pool)                       # 1.4232

nd <- data.frame(canopy = seq(40, 90, length.out = 100))
nd <- cbind(nd, predict(m_pool, nd, interval = "confidence"))
ggplot(orch, aes(canopy, yield)) +
  geom_point(aes(colour = orchard)) +
  geom_ribbon(data = nd, aes(y = fit, ymin = lwr, ymax = upr), alpha = 0.2) +
  geom_line(data = nd, aes(y = fit), linewidth = 1) +
  labs(x = "Canopy light interception (%)", y = "Kernel yield (kg/tree)") +
  theme_classic()

Q2. Every orchard moves toward zero, and the orchards with few trees move most. orchard02 (3 trees) goes from +1.92 to +1.55: it keeps 0.81 of its own estimate, against a shrinkage weight of 0.80. orchard11 (18 trees) goes from +1.65 to +1.62: it keeps 0.98, weight 0.96. With 3 trees, much of an orchard’s apparent difference could be the luck of which trees were measured, so the mixed model pulls it toward the average orchard; with 18 trees, the orchard’s own mean is trusted almost fully. The ratio and the weight agree to within a few hundredths. (For orchards whose effect is near zero, like orchard10, the ratio is unstable and means nothing; students should pick orchards with clearly nonzero effects.)

ids <- sort(unique(orch$orchard))
fe <- coef(m_fix)
fixed  <- c(0, fe[paste0("orchard", ids[-1])]) + fe[1] - fixef(m_mix)[1]
random <- ranef(m_mix)$orchard[ids, 1]
n <- as.numeric(table(orch$orchard)[ids])
sd_o <- attr(VarCorr(m_mix)$orchard, "stddev"); s <- sigma(m_mix)
w <- sd_o^2 / (sd_o^2 + s^2 / n)
round(data.frame(n, fixed, random, ratio = random / fixed, w), 2)
#   orchard02: n 3,  fixed 1.92, random 1.55, ratio 0.81, w 0.80
#   orchard11: n 18, fixed 1.65, random 1.62, ratio 0.98, w 0.96

ggplot(data.frame(fixed, random, n), aes(fixed, random)) +
  geom_abline(linetype = 2) + geom_hline(yintercept = 0, colour = "grey70") +
  geom_point(size = 2) + geom_text(aes(label = n), nudge_y = 0.15) +
  labs(x = "Orchard effect, fixed (own trees only)", y = "Orchard effect, random (shrunk)") +
  theme_classic()

Q3. No. lm() says the inoculant adds 0.81 kg/tree (SE 0.21, p = 0.0002). The mixed model says 0.43 kg/tree (SE 0.67, df 11.2, p = 0.53). Report the mixed model. The inoculant was applied to whole orchards, so the real sample size for testing it is 14 orchards (7 against 7), not 174 trees: the denominator df of about 11 reflects that. lm() treats every tree as independent evidence, and the “effect” is just that some high-yielding orchards happen to use the inoculant. Pseudoreplication. (The orchard means differ by only 0.14 kg/tree, 6.69 vs 6.55.)

coef(summary(lm(yield ~ canopy + inoculant, data = orch)))["inoculantyes", ]
#   0.8066  SE 0.2130  t 3.79  p 0.0002
m_inoc <- lmer(yield ~ canopy + inoculant + (1 | orchard), data = orch)
coef(summary(m_inoc))["inoculantyes", ]
#   0.4324  SE 0.6739  df 11.23  t 0.64  p 0.534

Q4. No evidence that orchards differ in their canopy response: χ² = 0.22 on 2 df, p = 0.90. The random-slope SD is 0.064 kg per 10 percentage points, against a mean slope of 0.80 per 10 points, so the orchard lines are nearly parallel. Keep the random-intercept model: the slope model adds two parameters (a slope SD and a correlation) and its AIC is about 4 higher. (Students who fit the slope model on raw canopy get a convergence warning: the slope SD is tiny on that scale. That is why the question rescales.)

orch$canopy10 <- (orch$canopy - 65) / 10
m1 <- lmer(yield ~ canopy10 + (1 | orchard), data = orch)
m2 <- lmer(yield ~ canopy10 + (canopy10 | orchard), data = orch)
VarCorr(m2)                    # canopy10 SD 0.0644
anova(m1, m2, refit = FALSE)   # Chisq 0.218, Df 2, p 0.897

Part 2: Ridge and Lasso

vars <- setdiff(paste0("bio", 1:19), "bio7")
X <- scale(as.matrix(wheat[, vars]))
y <- wheat$Flowering

Q5. The lm() coefficients are wild: bio1 (annual mean temperature) at −48.1 days per SD, with bio17 at −34.9, bio16 at −31.9 and bio13 at +28.1, and none has p < 0.15. Flowering time has an SD of only 9.9 days, so a 48-day change per SD of temperature is not believable: the 18 variables are so tangled that lm() balances huge positive and negative slopes against each other (Problem Set 5, VIF). On its own, bio1 has a slope of −7.8 days per SD.

Ridge at λ = 1 shrinks every coefficient to between −2.1 and +0.4 days per SD (bio1 −2.05, the largest), with the sum of absolute slopes falling from 271 to 13.8. At the largest λ in the path (7,719) every coefficient is 0, so ridge predicts the mean, 105.2 days, for every genotype: the null model. We scaled because the penalty adds up squared slopes, and a slope’s size depends on its variable’s units: bio4 (temperature seasonality) has an SD of 122, bio3 an SD of 0.4. Unscaled, ridge would shrink the small-unit variables’ large slopes much harder for no biological reason.

round(coef(lm(y ~ X))[-1], 1)        # bio1 -48.1, bio17 -34.9, bio16 -31.9, bio13 28.1, ...
sd(y)                                # 9.87
ridge <- glmnet(X, y, alpha = 0)
plot(ridge, xvar = "lambda")
round(coef(ridge, s = 1), 2)         # bio1 -2.05, bio9 -1.43, bio10 -1.34, ...
coef(ridge, s = max(ridge$lambda))   # all 0; intercept 105.17
sapply(wheat[, vars], sd)            # bio3 0.4 ... bio4 121.6

Q6. bio1 enters first, at λ = 7.03, and is the only variable in the model from λ = 7.03 down to 1.59. bio15 and bio16 join at λ = 1.45. Forward stepAIC() in Problem Set 5 Q9 also stopped at bio1 alone: on these data the lasso path and forward stepwise agree on the first and strongest variable. What the lasso does that ridge cannot: it sets coefficients to exactly zero, so it selects variables as it shrinks. Ridge keeps all 18 in at every λ (just small).

lasso <- glmnet(X, y, alpha = 1)
plot(lasso, xvar = "lambda")
cbind(lambda = round(lasso$lambda, 2), df = lasso$df)[1:20, ]   # df 1 from 7.03 to 1.59, 3 at 1.45
first <- apply(as.matrix(lasso$beta) != 0, 1, function(z) which(z)[1])
sort(first)[1:3]                                                # bio1 2, bio15 19, bio16 19

Part 3: Cross-Validation

Q7. With set.seed(206): lambda.min = 1.45, which keeps bio1, bio15 and bio16 (bio1 −6.29; the other two tiny); lambda.1se = 3.04, which keeps bio1 alone (−4.72). CV RMSE: 6.61 days at lambda.min, 7.02 at lambda.1se (null, at the largest λ: 9.99). Across seeds 1 to 5, lambda.1se keeps bio1 alone every time; lambda.min keeps 3, 5, 3, 6 and 3 variables, a different set depending on how the folds fall. The 1-SE rule gives the simpler and more stable answer for a small cost in CV error.

set.seed(206)
cv <- cv.glmnet(X, y, alpha = 1)
plot(cv)
cv$lambda.min; cv$lambda.1se                           # 1.446, 3.045
coef(cv, s = "lambda.min")                             # bio1 -6.29, bio15 -0.05, bio16 -0.01
coef(cv, s = "lambda.1se")                             # bio1 -4.72
sqrt(cv$cvm[cv$lambda == cv$lambda.min])               # 6.61
sqrt(cv$cvm[cv$lambda == cv$lambda.1se])               # 7.02
for (sd in 1:5) {
  set.seed(sd); cvx <- cv.glmnet(X, y, alpha = 1)
  print(rownames(coef(cvx, s = "lambda.1se"))[coef(cvx, s = "lambda.1se")[, 1] != 0])
}

Q8. RMSE on held-out genotypes: bio1 alone 6.31, lasso 7.10, all 18 9.08, null 10.04 days. The 18-variable model is barely better than predicting the mean: its huge, offsetting slopes (Q5) fit the noise in the training genotypes, which does not repeat in new ones (overfitting, Week 5). The lasso protects against that, landing close to bio1 alone because it mostly keeps bio1, but with a shrunk slope, so it is a little worse than the single-variable model here. Exact values shift a little with how the inner cv.glmnet() draws its folds; the ranking should not.

rmse <- function(o, p) sqrt(mean((o - p)^2))
set.seed(206)
fold <- sample(rep(1:10, length.out = nrow(wheat)))
pred <- matrix(NA, nrow(wheat), 4, dimnames = list(NULL, c("null", "bio1", "all18", "lasso")))
for (k in 1:10) {
  tr <- fold != k
  d_tr <- wheat[tr, ]; d_te <- wheat[!tr, ]
  pred[!tr, "null"]  <- mean(d_tr$Flowering)
  pred[!tr, "bio1"]  <- predict(lm(Flowering ~ bio1, d_tr), d_te)
  pred[!tr, "all18"] <- predict(lm(reformulate(vars, "Flowering"), d_tr), d_te)
  cvk <- cv.glmnet(as.matrix(d_tr[, vars]), d_tr$Flowering, alpha = 1)
  pred[!tr, "lasso"] <- predict(cvk, as.matrix(d_te[, vars]), s = "lambda.1se")
}
round(apply(pred, 2, function(p) rmse(wheat$Flowering, p)), 2)
#   null 10.04   bio1 6.31   all18 9.08   lasso 7.10

Q9. (a) Choosing the five columns once, on all 54 rows: CV RMSE 8.38, better than the null model’s 10.08. (b) Choosing inside each fold: 11.28, worse than the null. (b) is honest. In (a) the held-out genotypes had already been used to pick the columns: the five were chosen because they happened to line up with flowering time in all 54 rows, including the ones later “held out”. CV can only judge a procedure if every step of it, selection included, is repeated without the held-out fold.

set.seed(206)
noise <- matrix(rnorm(54 * 200), 54, 200, dimnames = list(NULL, paste0("n", 1:200)))
yy <- wheat$Flowering
top5 <- order(-abs(cor(noise, yy)))[1:5]
fold <- sample(rep(1:10, length.out = 54))
p_out <- p_in <- p_null <- numeric(54)
for (k in 1:10) {
  tr <- fold != k
  d <- data.frame(y = yy, noise[, top5])
  p_out[!tr] <- predict(lm(y ~ ., d[tr, ]), d[!tr, ])
  tk <- order(-abs(cor(noise[tr, ], yy[tr])))[1:5]
  d2 <- data.frame(y = yy, noise[, tk])
  p_in[!tr] <- predict(lm(y ~ ., d2[tr, ]), d2[!tr, ])
  p_null[!tr] <- mean(yy[tr])
}
rmse(yy, p_out)    # 8.38  chosen outside the folds: looks useful
rmse(yy, p_in)     # 11.28 chosen inside: worse than the mean
rmse(yy, p_null)   # 10.08

Q10. Random 10-fold: RMSE 1.09 kg/tree. Leave one orchard out: 1.49 kg/tree. Give a new grower 1.49. With random folds, every held-out tree’s orchard is also in the training data, so the prediction uses that orchard’s own random effect and the error is close to the tree-to-tree SD (1.03). A new orchard’s baseline is unknown, so the model can only predict the average orchard, and the orchard-to-orchard spread (SD 1.17) is added to the error. The fold structure must match how the model will be used: if you will predict new groups, hold out whole groups.

set.seed(206)
fold <- sample(rep(1:10, length.out = nrow(orch)))
p_rand <- p_grp <- numeric(nrow(orch))
for (k in 1:10) {
  tr <- fold != k
  m <- lmer(yield ~ canopy + (1 | orchard), data = orch[tr, ])
  p_rand[!tr] <- predict(m, orch[!tr, ], allow.new.levels = TRUE)
}
for (o in unique(orch$orchard)) {
  te <- orch$orchard == o
  m <- lmer(yield ~ canopy + (1 | orchard), data = orch[!te, ])
  p_grp[te] <- predict(m, orch[te, ], allow.new.levels = TRUE)
}
rmse(orch$yield, p_rand)   # 1.09
rmse(orch$yield, p_grp)    # 1.49